/**
 * 
 */
package com.lion.jacoco.manager.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lion.jacoco.common.GlobalVariable;
import com.lion.jacoco.common.PathUtil;
import com.lion.jacoco.dao.AppConfigDAO;
import com.lion.jacoco.dao.DatabasePopulator;
import com.lion.jacoco.dao.dataobject.AppConfigDO;
import com.lion.jacoco.manager.AppManager;
import com.lion.jacoco.manager.service.JacocoService;
import com.lion.jacoco.util.EnvUtil;

/**
 * AppManagerImpl.java. 2011-11-27下午8:20:03 @author LionBule.
 */
@Service
public class AppManagerImpl implements AppManager {
    private Logger            logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private GlobalVariable    globalVariable;
    @Autowired
    private AppConfigDAO      appConfigDAO;
    @Autowired
    private JacocoService     jacocoService;
    @Autowired
    private DatabasePopulator databasePopulator;

    @Override
    public void rebulid(AppConfigDO pdata) {
        if (pdata == null) {
            logger.error("pdata is null.");
            return;
        }
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            String basePath = pdata.getCodePath(globalVariable.getCodePath());
            File buildSh = new File(basePath, EnvUtil.isLinux() ? "build.sh" : "build.bat");
            File buildLog = new File(basePath, "logs" + File.separatorChar + pdata.getBaseName()
                    + System.currentTimeMillis() + ".log");
            if (!buildLog.getParentFile().exists()) {
                buildLog.getParentFile().mkdirs();
            }
            String command = EnvUtil.isLinux() ? "sh " + buildSh.getPath() : buildSh.getPath();
            Process process = Runtime.getRuntime().exec(command);

            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            bw = new BufferedWriter(new FileWriter(buildLog));
            String line = "";
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.write("\n");
            }
        } catch (Exception e) {
            logger.error("AppManager.rebulid", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                logger.error("AppManager.rebulid", e);
            }
        }
    }

    @Override
    public void InitSystem(int type) {
        if(type<=0){
            logger.error("AppManager.InitSystem. type<=0");
            return;
        }
        try {
            //drop & create table
            databasePopulator.populate();
            if (type == 2) {
                //delete all files
                PathUtil.del(globalVariable.getCodePath());
                PathUtil.del(globalVariable.getReportPath());
            }
        } catch (Exception e) {
            logger.error("AppManager.InitSystem", e);
        }
    }

    @Override
    public AppConfigDO queryById(int appId) {
        if (appId <= 0) {
            return null;
        }
        try {
            return appConfigDAO.queryById(appId);
        } catch (Exception e) {
            logger.error("AppManager.queryById", e);
        }
        return null;
    }

    @Override
    public String addApp(AppConfigDO pdata) {
        if (appConfigDAO == null) {
            return "参数异常";
        }

        try {
            int id = appConfigDAO.add(pdata);
            if (id > 0) {
                pdata.setId(id);
                PathUtil.mkdirs(pdata.getCodePath(globalVariable.getCodePath()));
            }
        } catch (Exception e) {
            logger.error("AppManager.addApp", e);
            return "系統异常";
        }

        return "新增成功";
    }

    @Override
    public String refresh(int appId) {
        try {
            AppConfigDO appConfigDO = appConfigDAO.queryById(appId);
            jacocoService.createReport(appConfigDO);
        } catch (Exception e) {
            logger.error("AppManager.addApp", e);
        }

        return "ok";
    }

    @Override
    public List<AppConfigDO> queryAllApp() {
        try {
            return appConfigDAO.queryAll();
        } catch (Exception e) {
            logger.error("AppManager.queryAllApp", e);
        }
        return new ArrayList<AppConfigDO>();
    }

    @Override
    public String deleteAppById(int appId) {
        if (appId <= 0) {
            return "参数异常";
        }
        try {
            AppConfigDO pdata = appConfigDAO.queryById(appId);

            //删除code目录
            String basePath = pdata.getCodePath(globalVariable.getCodePath());
            PathUtil.del(basePath);

            //删除应用记录
            appConfigDAO.delete(appId);

        } catch (Exception e) {
            logger.error("AppManager.deleteAppById", e);
            return "系统异常id=" + appId;
        }
        return "删除成功id=" + appId;
    }

    @Override
    public String updateAppById(AppConfigDO pdata) {
        if (appConfigDAO == null) {
            return "参数异常";
        }
        try {
            appConfigDAO.updateById(pdata);
        } catch (Exception e) {
            logger.error("AppManager.updateAppById", e);
            return "系统异常";
        }

        return "更新成功";
    }

}
